<template>
  <!-- 搜索建议 -->
  <div class="search-suggestion">
    <van-cell
      icon="search"
      @click="$emit('search', text)"
      v-for="(text, index) in suggestions"
      :key="index"
    >
      <div slot="title" v-html="highlight(text)"></div>
    </van-cell>
  </div>
</template>

<script>
import { getSearchSuggestions } from "@/api/search.js";
import { debounce } from "lodash";
export default {
  props: {
    searchText: String,
  },
  data() {
    return {
      suggestions: [],
    };
  },
  methods: {
    async loadSearchSuggestions(q) {
      try {
        const { data } = await getSearchSuggestions({ q });
        this.suggestions = data.data.options;
      } catch (error) {
        this.$toast("数据获取失败，请稍后重试");
      }
    },
    highlight(text) {
      const reg = new RegExp(this.searchText, "gi");

      if (text) {
        return text.replace(
          reg,
          `<span class="active">${this.searchText}</span>`
        );
      }
    },
  },
  watch: {
    searchText: {
      handler: debounce(function (val) {
        console.log(val);
        this.loadSearchSuggestions(val);
      }, 200),
      //   handler(val) {
      //     this.loadSearchSuggestions(val);
      //   },
      immediate: true,
    },
  },
};
</script>

<style lang="scss" scoped>
.search-suggestion {
  /deep/ span.active {
    color: #3296fa;
  }
}
</style>
